/**
 * 这个js是进入程序画拓扑图
 */
var showTopoFrontBtnCount=0;
var offloadHost = 'localhost';
var offloadPort = '8778';
var offloadUrlPrefix = 'http://' + offloadHost + ':' +offloadPort;
window.onload=function () {
    jtopo1();
    showTopoDiagramLogic();
    //使用eq来选择第几个元素
    console.log('当前盒子client宽度为'+document.body.clientWidth);
    console.log('当前盒子offset高度为'+document.body.offsetHeight);
    console.log('当前window高度为'+window.screen.height);
    console.log('all_tab宽度'+0.9*document.getElementById("all_tab").offsetWidth);
    layui.use('element', function(){
        var element = layui.element;
        //获取hash来切换选项卡，假设当前地址的hash为lay-id对应的值
    });

};

//对于展示拓扑图按钮进行监听赋予
function showTopoDiagramLogic() {
    // $("#showTopoFrontBtn").css("top",((document.body.offsetHeight)-40)+"px");
    // $("#all_topo_block").css("top",(($("#all_tab").offset().top)+10)+"px");//layuitab自带上边距
    console.log("========"+document.body.offsetHeight);
    // console.log("按钮的位置"+document.getElementById("showTopoFrontBtn").offsetTop);
    $('#showTopoFrontBtn').click(function () {
        console.log("按钮的位置"+document.getElementById("showTopoFrontBtn").offsetTop);
        if(showTopoFrontBtnCount%2===0){
            $("#all_mask").css("display","block");
            $('#showTopoFrontBtn').html("<i class='layui-icon layui-icon-left' style='font-size: 17px'></i>");
            $("#all_topo_block").css("transform","translateX("+((document.body.clientWidth-$("#kk").attr("width"))/2-5)+"px) " +
                                                 "translateY(-"+(document.body.clientHeight-$("#kk").attr("height"))/2+"px)");
            $("#all_topo_block").css("transition","0.5s");
            $("#all_topo_block").css("background-color","ghostwhite");
        }
        else{
            $("#all_topo_block").css("background-color","");
            $("#all_topo_block").css("transform","");
            $("#all_topo_block").css("transition","0.5s");
            $('#showTopoFrontBtn').html("<i class='layui-icon layui-icon-search' style='font-size: 17px'></i>");
            $("#all_mask").css("display","none");
        }
        showTopoFrontBtnCount++;
    })
}

function jtopo1() {
    var mecnode=[];
    var termnode = [];
    $(function () {
        $.ajax({
            type: 'get',
            // url:'http://localhost:8778/Mec/getAllMec',
            url: offloadUrlPrefix + '/offload/Mec/getAllMec',
            async : false,
            success:function (msg1) {
                mecnode = msg1;
                console.info(msg1);
            },
            error: function (msg1) {
                alert(msg1.error());
            }
        })
    });
    $(function () {
        $.ajax({
            type: 'get',
            // url:'http://localhost:8778/NodeTerm/getAllNodeTerm',
            url: offloadUrlPrefix + '/offload/NodeTerm/getAllNodeTerm',
            async : false,
            success:function (msg2) {
                termnode = msg2;
            },
            error: function (msg2) {
                alert(msg2.error());
            }
        })
    });
    console.log('这里打印了mecnode呀', mecnode);
    var canvas = document.getElementById('kk');
    var stage = new JTopo.Stage(canvas);
    //显示工具栏
    var scene = new JTopo.Scene();
    stage.add(scene);
    // scene.background = '../common/images/bg.jpg';
    var cloudNode = new JTopo.Node('Mec'+mecnode[0].mecId);
    //cloudNode.setSize(30, 26); //设置方块大小
    cloudNode.id = 100;
    cloudNode.textPosition = 'Bottom_Center';
    cloudNode.fontColor= '0, 0, 0'; //字体颜色
    // cloudNode.setLocation(470, 280);
    cloudNode.setLocation(250, 285);
    cloudNode.layout = {type: 'circle', radius: 180};
    //cloudNode.layout = {type: 'tree', direction: 'top',width: 100, height: 150};

    cloudNode.setImage('../../static/img/edgecompute/00.png',true);
    scene.add(cloudNode);
    for (var j = 0; j < termnode.length; j++) {
        if(termnode[j].loginMecId==mecnode[0].mecId) {
            var vmNode = new JTopo.Node('Term' + termnode[j].termId);
            //vmNode.radius = 10;
            vmNode.id = termnode[j].termId;
            vmNode.fontColor= '0, 0, 0';
            var x = termnode[j].termId%5;
            vmNode.setImage('../../static/img/edgecompute/c'+x+'.png',true);
            vmNode.setSize(32,32);
            vmNode.setLocation(scene.width * Math.random(), scene.height * Math.random());
            scene.add(vmNode);
            vmNode.click(function (event) {
                    console.log("hello");
                    console.log(this.id);
                    // layer.msg("点击了一级无子终端："+this.id);
                    generateTerminalWindow_topo(this.id);

            });
            scene.add(new JTopo.Link(cloudNode, vmNode));
        }
    }

    //中心结点
    // cloudNode.mouseover(function(deviceTarget2){
    //     console.info(deviceTarget2);
    //     console.info(cloudNode);
    //
    //     var deviceTarget = $("<div style='width:50px;height:50px;position:absolute;'></div>").attr("id", 'mec'+mecnode[0].mecId)
    //         .css({
    //             top: deviceTarget2.pageY ,
    //             left: deviceTarget2.pageX-50
    //         });
    //     $("body").append(deviceTarget);
    //     var content = `<div style="min-width:100px;">
    //                                  &nbsp;&nbsp;MecID: ${mecnode[0].mecId} <br>
    //                                 &nbsp;&nbsp;Mec速率: ${mecnode[0].mecRate} <br>
    //                                 &nbsp;&nbsp;Mec功率: ${mecnode[0].connectPower} <br>
    //                                 </div>`;
    //     // 弹出层 tips：【1234弹出位置，弹出框颜色】
    //     layer.tips(content, "#"+'mec'+mecnode[0].mecId, {
    //         tips: [1, '#cc95a1'],
    //         time: 0
    //     });
    // });
    cloudNode.click(function (event) {
       // layer.msg("点击了云中心终端:"+mecnode[0].mecId);
        mecLayer(mecnode[0].mecId);
    });
    // cloudNode.mouseout(function(){
    //     $("#"+mecnode[0].mecId).remove();
    //     layer.closeAll();
    // });


    // 添加剩下的mec和终端
    for (var i = 1; i < mecnode.length; i++) {
        var node = new JTopo.Node('Mec'+mecnode[i].mecId);
        node.id = mecnode[i].mecId;
        node.fontColor= '0, 0, 0';
        node.setImage('../../static/img/edgecompute/00.png',true);
        node.setLocation(scene.width * Math.random(), scene.height * Math.random());
        node.layout = {type: 'tree', direction: 'top',width: 50, height: 70};
        scene.add(node);
        //监听移过
        // node.mouseover(function(deviceTarget3){
        //     var t = deviceTarget3.target.id;
        //     console.info(t);
        //     var deviceTarget = $("<div style='width:50px;height:50px;position:absolute;'></div>").attr("id", 'mec'+t)
        //         .css({
        //             top: deviceTarget3.pageY,
        //             left: deviceTarget3.pageX-50
        //         });
        //     $("body").append(deviceTarget);
        //     var content = `<div style="min-width:100px;">
        //                              &nbsp;&nbsp;MecID: ${mecnode[t-1].mecId} <br>
        //                             &nbsp;&nbsp;Mec速率: ${mecnode[t-1].mecRate} <br>
        //                             &nbsp;&nbsp;Mec功率: ${mecnode[t-1].connectPower} <br>
        //                             </div>`;
        //     // 弹出层 tips：【1234弹出位置，弹出框颜色】
        //     layer.tips(content, "#"+'mec'+t, {
        //         tips: [1, '#cc95a1'],
        //         time: 0
        //     });
        // });
        // node.mouseout(function(){
        //     //var ii = event.target.id;
        //     //$("#"+ii).remove();
        //     layer.closeAll();
        // });
        node.click(function (event) {
           // layer.msg("点击了二级MEC"+this.id);
            mecLayer(this.id);
        });
        var link = new JTopo.Link(cloudNode, node);
        link.strokeColor = '255,165,0';
        link.dashedPattern = 5; //开启曲线
        scene.add(link);
        for (var j = 0; j < termnode.length; j++) {
            if(termnode[j].loginMecId==mecnode[i].mecId) {
                var vmNode = new JTopo.Node('Term' + termnode[j].termId);
                vmNode.id = termnode[j].termId;
                vmNode.fontColor= '0, 0, 0';
                vmNode.fillStyle = '0, 0, 255';
                //vmNode.setImage('../../images/3s.png',true);
                var x = termnode[j].termId % 5;
                vmNode.setImage('../../static/img/edgecompute/c'+ x+ '.png',true);

                vmNode.textPosition = 'Top_Center';
                vmNode.setLocation(scene.width * Math.random(), scene.height * Math.random());
                scene.add(vmNode);

                vmNode.click(function (event) {
                   layer.msg("点击了二级终端："+this.id);
                   generateTerminalWindow_topo(this.id);
                });
                scene.add(new JTopo.Link(node, vmNode));
            }
        }
    }

    JTopo.layout.layoutNode(scene, cloudNode, true);
    scene.addEventListener('mouseup', function (e) {
        if (e.target && e.target.layout) {
            JTopo.layout.layoutNode(scene, e.target, true);
        }
    });
}

//构建终端对应的弹窗
function generateTerminalWindow_topo(terminalId){
    layui.use(['table', 'form', 'layer','jquery'], function() {
        layer.open({
            type:1,  //1公告，2iframe
            title:false, //弹窗标题
            closeBtn:false,
            area:['630px','500px'],
            shade:0.8,
            id: 'LAY_layuipro', //设定一个id，防止重复弹出
            // btn:['添加','取消'],
            // btnAlign: 'c',//文字居中
            moveType: 1, //拖拽模式，0或者1
            content:
            // '<i class="layui-icon layui-icon-close" style="margin-top:10px;margin-right: 10px;font-size: 15px"></i>'
                '<div id="layer_close_btn" style="position: fixed;margin:0;padding-left: 6px;padding-top: 3px;width:29px;height: 34px;border-radius: 3px">' +
                '   <i class="layui-icon layui-icon-return" style="font-size: 23px"></i>' +
                '</div>' +
                '<div style="width: 92%;margin:20px auto 0">' +
                '   <fieldset class="layui-elem-field layui-field-title">' +
                '       <legend>'+terminalId+'号终端的父任务列表</legend>' +
                '   </fieldset>' +
                '</div>' +
                '<div style="width: 90%;margin:0 auto">\n' +
                '   <table style="border: none" class="layui-hide" id="oneTerminalTable" lay-filter="oneTerminalTable"></table>\n' +
                '</div>' +
                //切割后表格
                '<div id="one_cut_table_block" style="display: none">' +
                '   <div style="width: 92%;margin:25px auto 0;">' +
                '       <fieldset class="layui-elem-field layui-field-title">' +
                '           <legend id="one_cut_table_title">0号切割表格</legend>' +
                '       </fieldset>' +
                '   </div>' +
                '   <div style="width: 90%;margin: 0 auto">' +
                '       <table style="border: none" class="layui-hide" id="oneCutTable" lay-filter="oneCutTable"></table>' +
                '   </div>' +
                '</div>' +
                //切割拓扑图
                '<div style="width: 92%;margin:25px auto 0">' +
                '   <fieldset class="layui-elem-field layui-field-title">' +
                '       <legend id="one_cut_topo_title">父任务切割示意图：(尚未指定)</legend>' +
                '   </fieldset>' +
                '</div>' +
                '<div style="width: 90%;min-height: 230px;border: 2px solid #e8e8e8;margin: 0 auto 40px;">' +
                //没有切分时显示部分
                '   <div id="no_cut_tips" style="width: 40%;height: 40%;margin: 70px auto;display: block">' +
                '       <div style="width: 100%;height: 60%;text-align: center">' +
                '           <i class="layui-icon layui-icon-tips" style="font-size: 47px;color: #999999;"></i>' +
                '       </div>' +
                '       <div style="width: 100%;height: 40%;text-align: center"><h2 style="color: #999999">这里空空如也</h2></div>' +
                '   </div>' +

                //在这里加入拓扑图
                '   <div id="one_cut_topo_diagram" style="width:100%;min-height:230px;display: none">' +
                '       <div id="one_cut_topo_diagram_container" style="width: 90%;margin:15px auto;height: 200px;border: 1px solid pink;"></div>' +
                '   </div>' +
                '</div>'
        });
        termtasklist(terminalId);
        $('#layer_close_btn').on('click',function () {
            layer.closeAll();
            generatePieBlock();
            // generateBarBlock();
            generateNotOffloadTable();
        })
    });

}


